package com.hurl.waguji.biz.collect;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.ScrollableResults;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.testng.log4testng.Logger;

import com.hurl.waguji.base.dao.HibernateDao;
import com.hurl.waguji.base.dao.HibernateService;
import com.hurl.waguji.persistence.DmGpBO;

public class GpdmIterator {
	private static final Logger log = Logger.getLogger(GpdmIterator.class);
	private int count = 0;
	private List<CollectHandler> handlerList = new ArrayList<CollectHandler>();
	
	public void addHandler(CollectHandler handler){
		handlerList.add(handler);
	}
	
	public void start(){
		HibernateDao dao = HibernateService.getDao();
		for(CollectHandler handler : handlerList){
			try{
				handler.startup(dao);
			}catch(Throwable t){
				log.error(t.getMessage(),t);
				t.printStackTrace();
			}
		}
		ScrollableResults results = dao.createCriteria(DmGpBO.class).add(Restrictions.eq("flag", 'Y')).addOrder(Order.asc("gpDm")).setReadOnly(true).scroll();
		DmGpBO gp = null;
		while(results.next()){
			gp = (DmGpBO)results.get(0);
			for(CollectHandler handler : handlerList){
				try{
					handler.execute(gp, dao);
				}catch(Throwable t){
					log.error(t.getMessage(),t);
				}
			}
			count++;
			if(count%20==0){
				dao.flush();
				dao.clear();
			}
		}
		for(CollectHandler handler : handlerList){
			try{
				handler.shutdown(dao);
			}catch(Throwable t){
				log.error(t.getMessage(),t);
				t.printStackTrace();
			}
		}
	}
}
